﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ubiety.Dns.Core;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Dto.Request.Login;
using XuanXiang.Infrastructure.Dto.Response;
using XuanXiang.Infrastructure.Dto.Response.System;
using XuanXiang.Infrastructure.EFCore.MySql;
using XuanXiang.Infrastructure.IOC;
using XuanXiang.Infrastructure.Redis;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.EFCore;
using XuanXiang.Service.Interface;


namespace XuanXiang.Service.Instance
{
    [Inject_]
    public class Login_Service :Base_Service, I_Login_Service
    {
        private readonly Login_IOC _login_IOC;
        private readonly Supplier_IOC _supplier_IOC;
        private readonly Merchant_IOC _merchant_IOC;
        private readonly IConfiguration _configuration;
        private readonly RedisStringService _redisStringService;

        public Login_Service(RedisStringService redisStringService,
            Login_IOC login_ioc,
            Merchant_IOC merchant_IOC,
            Supplier_IOC supplier_IOC,
            IConfiguration configuration)
        {
            _login_IOC=login_ioc;
            _supplier_IOC = supplier_IOC;
            _merchant_IOC = merchant_IOC;
            _configuration = configuration;
            _redisStringService = redisStringService;
        }

        /// <summary>
        /// 检查登录
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Users_Dto Check_Login(string code,string account)
        {
            var redis = _configuration["Redis:Keys:Check_Login"];


            //获取redis中的用户信息
            var u= _redisStringService.Get<string>(code);
            if (!string.IsNullOrEmpty(u)) {
                return JsonConvert.DeserializeObject<Users_Dto>(u)!;
            }

            
            
            var jwt= _redisStringService.Get<string>(redis+account);//code
            if (code == jwt)
            {
                //返回登录的用户信息
                var user = _login_IOC._sysUser_EFCore.GetAll(d => d.Uaccount == account)
                     .Select(d => new Users_Dto()
                     {
                         id=d.Uid,
                         account=d.Uaccount,
                         name=d.Uname
                     }).Single();
                //将用户存在redis中
                _redisStringService.Set(code, JsonConvert.SerializeObject(user),DateTime.Now.AddSeconds(120));
                return user;
            }
            else {
                return null;
            }

           
        }


        /// <summary>
        /// 初始化用户密码
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Init_User()
        {
            //初始化商户密码
            /* var user = await _merchant_IOC._merchant_EFCore.GetAll().ToListAsync();
             user.ForEach(d =>
             {
                 var salt = Config.GUID2();
                 d.MSalt = salt;
                 d.MPassword = EncryptUtil.LoginMd5("123456", salt);

             });

             _merchant_IOC._merchant_EFCore.UpdateRange(user);
             _merchant_IOC._merchant_EFCore.SaveChanges();
             return Get_Result(0);*/

            //初始化用户密码
           /* var user = await _login_IOC._sysUser_EFCore.GetAll().ToListAsync();
            user.ForEach(d =>
            {
                var salt = Config.GUID2();
                d.Usalt = salt;
                d.Upassword = EncryptUtil.LoginMd5("123456", salt);

            });

            _login_IOC._sysUser_EFCore.UpdateRange(user);
            _login_IOC._sysUser_EFCore.SaveChanges();
            return Get_Result(0);*/

            //初始供应商密码
            var supplier = await _supplier_IOC._supplier_EFCore.GetAll().ToListAsync();
            supplier.ForEach(d =>
            {
                var salt = Config.GUID2();
                d.Ssalt = salt;
                d.Spassword = EncryptUtil.LoginMd5("123456", salt);

            });

            _supplier_IOC._supplier_EFCore.UpdateRange(supplier);
            _supplier_IOC._supplier_EFCore.SaveChanges();
            return Get_Result(0);
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Logins(Login_dto dto)
        {
            var iq = _login_IOC._sysUser_EFCore.GetAll(d => d.Uaccount == dto.account);
            if (!await iq.AnyAsync())
            {
                return Get_Result(-1, "账号或者密码错误");
            }
            var user =await iq.SingleAsync();


            var pwd = EncryptUtil.LoginMd5(dto.password!, user.Usalt!);
            if (user.Upassword != pwd) {
                return Get_Result(-1, "账号或者密码错误");
            }

            if (user.UisBan == 1) {
                return Get_Result(-1, "账号已禁用");
            }
           

            //添加登录日志
            SysLoginLog log= new SysLoginLog() { 
            Llcode=dto.code,
            Llid=Config.GUID2(),
            LlcreateTime=DateTime.Now,
            Llresult=0,
            Lluid=user.Uid
            };
            if (user.UisActive == 0) {
                user.UisActive = 1;
                _login_IOC._sysUser_EFCore.Update(user);
            }

            //事务
           var result= _login_IOC._sysLoginLog_EFCore.Transactions(_login_IOC._sysUser_EFCore);

            //保存code到redis
            var jwt = _configuration["Redis:Keys:Check_Login"];


            _redisStringService.Set<String>(jwt + user.Uaccount, dto.code!,DateTime.Now.AddSeconds(86400));



            return Get_Result(result?0:-1);



        }


    }
}
